package com.xc.ksxt.controller;

import com.xc.common.object.LayuiTableResponse;
import com.xc.common.object.PageInfo;
import com.xc.common.object.ResponseEntity;
import com.xc.common.tool.Helper;
import com.xc.db.tables.Choice;
import com.xc.db.tables.LibChoice;
import com.xc.db.tables.Question;
import com.xc.db.tables.Tag;
import com.xc.ksxt.entity.*;
import com.xc.ksxt.service.*;
import com.xc.ksxt.vo.QuestionVO;
import com.xc.sys.entity.SysDictEntity;
import com.xc.sys.entity.SysUserEntity;
import com.xc.sys.service.SysDictService;
import com.xc.sys.service.SysUserService;
import com.xc.sys.vo.SysUserVO;
import org.apache.commons.lang3.StringUtils;
import org.jooq.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.jooq.impl.DSL.field;
import static org.jooq.impl.DSL.table;
@RestController
@RequestMapping("/question")
@CrossOrigin
public class QuestionController {
    @Autowired
    private DSLContext dsl;
    @Autowired
    private QuestionService libService;
    private LibChoice LIBCHOICETB = LibChoice.LIB_CHOICE.as("LIBCHOICETB");
    @Autowired
    private LibChoiceService libChoiceService;
    @Autowired
    private LibQuestionService libQuestionService;
    @Autowired
    private ChoiceService choiceService;
    @Autowired
    private QuestionService questionService;
    private Choice CHOICE = Choice.CHOICE.as("CHOICE");
    private Question QUESTION = Question.QUESTION.as("QUESTION");
    private Tag TAG = Tag.TAG.as("TAG");
    @CrossOrigin(origins = "*", allowedHeaders = {"*"}, methods = {RequestMethod.GET})
    @RequestMapping({"/getPageList"})
    public LayuiTableResponse<QuestionVO> getPageList(HttpServletRequest request) {
        LayuiTableResponse<QuestionVO> ltr = new LayuiTableResponse<>();
        Condition cond = QUESTION.ID.notEqual(-1l);
        String paperId = request.getParameter("paperId");
        Integer limit = Integer.valueOf(request.getParameter("limit"));
        Integer page = Integer.valueOf(request.getParameter("page"));
        if (StringUtils.isNotBlank(paperId)) {
            cond = cond.and(QUESTION.PAPER_ID.eq(Long.valueOf(paperId)));
        }
        Long count = libService.count(cond);
        ltr.setCount(count);
        PageInfo<QuestionEntity> pageInfo = new PageInfo<>(limit, page);
        Result<Record> list = libService.select(cond, pageInfo,QUESTION.ORDERNO.asc(),QUESTION.CREATE_TIME.desc());
        List<QuestionVO> libEntityList = list.into(QuestionVO.class);
        for (QuestionVO libEntity : libEntityList){
            setTxt(libEntity);
        }
        ltr.setData(libEntityList);
        return ltr;
    }

    private void setTxt(QuestionVO libEntity) {
        SysUserVO user = SysUserService.getFrameCaches(libEntity.getCreateUserId());
        libEntity.setCreateUserName(user==null?"":user.getName());
        if(libEntity.getCategoryId()!=null){
            String cname = dsl.select(field("name")).from(table("lib_category")).where(field("id").eq(Long.valueOf(libEntity.getCategoryId()))).fetchOneInto(String.class);
            libEntity.setCategoryName(cname);
        }
        if(libEntity.getChapterId()!=null){
            Result<Record1<Object>> r = dsl.select(field("name")).from(table("chapter")).where(field("id").eq(libEntity.getChapterId())).fetch();
            if(r.size()!=0){
                libEntity.setChapterName(r.get(0).get(0,String.class));
            }
        }
        if(libEntity.getQuestionType()<=3){
            List<ChoiceEntity> choiceList = choiceService.select(CHOICE.QUESTION_ID.eq(Long.valueOf(libEntity.getId())), CHOICE.INDEX_LETTER.asc());
            StringBuilder buf = new StringBuilder();
            for (ChoiceEntity libChoiceEntity : choiceList) {
                buf.append(libChoiceEntity.getIndexLetter() + "." + libChoiceEntity.getText());
                if(!libChoiceEntity.getText().endsWith("<br>")){
                    buf.append("<br>");
                }
            }
            if(libEntity.getText().length()<24){
                libEntity.setText2(libEntity.getText() + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br>" + buf);
            }else{
                libEntity.setText2(libEntity.getText() + "<br>" + buf);
            }

        }else {
            libEntity.setText2(libEntity.getText());
        }
        SysDictEntity dict = SysDictService.getFromCaches("question-type," + libEntity.getQuestionType());
        libEntity.setQuestionTypeTxt(dict==null?"":dict.getName());
        if(libEntity.getPianId()!=null){
            PianEntity pian = PianService.getFromCaches(libEntity.getPianId());
            libEntity.setPianName(pian==null?"":pian.getName());
        }
        if(libEntity.getJieId()!=null){
            JieEntity jie = JieService.getFromCaches(libEntity.getJieId());
            libEntity.setJieName(jie==null?"":jie.getName());
        }
        if(libEntity.getChapterId()!=null){
            Result<Record1<Object>> r = dsl.select(field("name")).from(table("chapter")).where(field("id").eq(libEntity.getChapterId())).fetch();
            if(r.size()!=0){
                libEntity.setChapterName(r.get(0).get(0,String.class));
            }
        }
    }

    @RequestMapping({"/getById"})
    public QuestionVO getById(Long id) {
        Record r = libService.getRecordById(id);
        QuestionVO entity = r.into(QuestionVO.class);
        setTxt(entity);
        return entity;
    }

    @RequestMapping({"/save"})
    public ResponseEntity<QuestionEntity> save(@RequestBody HashMap<String,String> params, HttpServletRequest request) {
        ResponseEntity<QuestionEntity> res = new ResponseEntity<>();
        QuestionEntity libEntity = Helper.map2Bean(new QuestionEntity(), params);
        libService.save(libEntity);
        return res;
    }
    @RequestMapping({"/updateOrderno"})
    public ResponseEntity<QuestionEntity> updateOrderno(@RequestBody HashMap<String,String> params) {
        Long id = Long.valueOf(params.get("id"));
        Integer orderno = Integer.valueOf(params.get("orderno"));
        ResponseEntity<QuestionEntity> res = new ResponseEntity<>();
        QuestionEntity lq = questionService.getEntityById(id);
        lq.setOrderno(orderno);
        questionService.update(lq);
        return res;
    }
    @RequestMapping({"/updateLibQuestionId"})
    public ResponseEntity<QuestionEntity> updateLibQuestionId(@RequestBody HashMap<String,String> params) {
        String libQuestionId = params.get("libQuestionId");
        LibQuestionEntity libQuestionEntity = libQuestionService.getEntityById(Long.valueOf(libQuestionId));
        String id = params.get("id");
        ResponseEntity<QuestionEntity> res = new ResponseEntity<>();
        QuestionEntity lq = questionService.getEntityById(Long.valueOf(id));
        updateQuestion(libQuestionEntity,lq);
        questionService.update(lq);
        return res;
    }
    private void updateQuestion(LibQuestionEntity lqe, QuestionEntity qe) {
        qe.setLg(lqe.getLg());
        qe.setDifficulty(lqe.getDifficulty());
        qe.setLibId(lqe.getLibId());
        qe.setOrderno(lqe.getOrderno());
        qe.setAnalysis(lqe.getAnalysis());
        qe.setCategoryId(lqe.getCategoryId());
        qe.setPianId(lqe.getPianId());
        qe.setJieId(lqe.getJieId());
        qe.setChapterId(lqe.getChapterId());
        qe.setContentType(lqe.getContentType());
        qe.setSource(lqe.getSource());
        qe.setText(lqe.getText());
        qe.setQuestionType(lqe.getQuestionType());
        qe.setLibQuestionId(lqe.getId());
        questionService.update(qe);
        dsl.delete(CHOICE).where(CHOICE.QUESTION_ID.eq(Long.valueOf(qe.getId()))).execute();
        List<LibChoiceEntity> choiceList = libChoiceService.select(LIBCHOICETB.LIB_QUESTION_ID.eq(Long.valueOf(lqe.getId())));
        for (LibChoiceEntity lce : choiceList) {
            ChoiceEntity ce = new ChoiceEntity();
            ce.setText(lce.getText());
            ce.setLibId(lce.getLibId());
            ce.setLibChoiceId(lce.getId());
            ce.setLibQuestionId(lqe.getId());
            ce.setCreateTime(LocalDateTime.now());
            ce.setRight(lce.getRight());
            ce.setAnswerText(lce.getAnswerText());
            ce.setIndexLetter(lce.getIndexLetter());
            ce.setQuestionId(qe.getId());
            ce.setPaperId(qe.getPaperId());
            choiceService.insert(ce);
        }
        lqe.setLastUseDate(LocalDate.now());
        libQuestionService.update(lqe);
    }
    @RequestMapping({"/delete"})
    public LayuiTableResponse<QuestionEntity> delete(@RequestBody Map<String,String> params) {
        String ids = params.get("ids");
        Long[] idarr = Helper.str2longArr(ids);
        LayuiTableResponse<QuestionEntity> ltr = new LayuiTableResponse<>();
        for (Long id : idarr) {
            QuestionEntity m = questionService.getEntityById(id);
            m.setDelFlag(-1);
            questionService.update(m);
        }
        return ltr;
    }

}
